<%@page contentType="text/html;charset=UTF-8"%>
<%@ include file="/commons/taglibs.jsp"%>
<!DOCTYPE html>
<link href="resources/ztree/zTreeStyle/zTreeStyle.css" rel="stylesheet"
	type="text/css" />
<script src="resources/ztree/jquery.ztree.all-3.1.min.js"
	type="text/javascript"></script>
	<script src="resources/jquery.json-2.3.js"
	type="text/javascript"></script>
<SCRIPT type="text/javascript">

<!--

var IDMark_A = "_a";


var setting = {
		view: {
			addHoverDom: addHoverDom,
			removeHoverDom: removeHoverDom,
			addDiyDom: addDiyDom,
			selectedMulti: false
		},
		edit: {
			enable: true,
			editNameSelectAll: true
		},
		data: {
			simpleData: {
				idKey: "id",
				pIdKey: "parent_id",
				enable: true
			}
		},
		callback: {
			beforeDrag: beforeDrag,
			beforeDrop: beforeDrop,
			beforeEditName: beforeEditName,
			beforeRemove: beforeRemove,
			beforeRename: beforeRename,
			onRemove: onRemove,
			onRename: onRename,
			beforeClick: beforeClick
		}
	};
		 		
function loadTree() {
	 $.ajax({  
	        async : false,  
	        cache:false,  
	        type: 'POST',  
	        dataType : "json",  
	        url: "${ctx}/menu/dotree",//请求的action路径  
	        error: function () {//请求失败处理函数  
	            alert('请求失败');  
	        },  
	        success:function(data){ //请求成功后处理函数。    
	        	var treeObj =$.fn.zTree.init($("#treeDemo"), setting, data);
	        	treeObj.expandAll(true);
	        }  
	    });  	 
	
}

		$(document).ready(function(){
			loadTree();	
			$("#btnSvaeTree").click( function () {
				var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
				var nodes = treeObj.transformToArray(treeObj.getNodes());
				var trees=new Array()	
				for(var i=0;i<nodes.length;i++){ 
				    var tree = {};
				    tree.id=nodes[i]["id"];
				    tree.parent_id=nodes[i]["parent_id"];
				    tree.name=nodes[i]["name"];
				    trees[i]=tree;
				}
				var jsonData=$.toJSON(trees);
				alert(jsonData);
				$.ajax({  
			        async : false,  
			        cache:false,  
			        type: 'POST',
			        dataType: 'json',
			        contentType: 'application/json;charset=utf-8',
			        data :jsonData,
			        url: "${ctx}/menu/savetree",//请求的action路径  
			        error: function () {//请求失败处理函数  
			            alert('请求失败');  
			        },  
				    success: function(result) { 
				        alert(result.msg); 
				    }
			    });  			
			 }); 
			$("#copy").bind("click", copy);
			$("#cut").bind("click", cut);
			$("#paste").bind("click", paste);
		});
		

		var className = "dark";
		function beforeDrag(treeId, treeNodes) {
			for (var i=0,l=treeNodes.length; i<l; i++) {
				if (treeNodes[i].drag === false) {
					return false;
				}
			}
			return true;
		}
		function beforeDrop(treeId, treeNodes, targetNode, moveType) {
			return targetNode ? targetNode.drop !== false : true;
		}
		
		function beforeEditName(treeId, treeNode) {
			className = (className === "dark" ? "":"dark");
			showLog("[ "+getTime()+" beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
			return ;
			//return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
		}
		function beforeRemove(treeId, treeNode) {
			className = (className === "dark" ? "":"dark");
			showLog("[ "+getTime()+" beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
			return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
		}
		function onRemove(e, treeId, treeNode) {
			showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
		}
		function beforeRename(treeId, treeNode, newName) {
			className = (className === "dark" ? "":"dark");
			showLog("[ "+getTime()+" beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			if (newName.length == 0) {
				alert("节点名称不能为空.");
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				setTimeout(function(){zTree.editName(treeNode)}, 10);
				return false;
			}
			return true;
		}
		function onRename(e, treeId, treeNode) {
			showLog("[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			
		}
		function showLog(str) {
			var log = $("#log");
			log.append("<li class='"+className+"'>"+str+"</li>");
			if(log.children("li").length > 15) {
				log.get(0).removeChild(log.children("li")[0]);
			}
		}
		function getTime() {
			var now= new Date(),
			h=now.getHours(),
			m=now.getMinutes(),
			s=now.getSeconds(),
			ms=now.getMilliseconds();
			return (h+":"+m+":"+s+ " " +ms);
		}

		var newCount = 1;
		function addHoverDom(treeId, treeNode) {
			var maxID=getmaxId();
			var sObj = $("#" + treeNode.tId + "_span");
			if (treeNode.editNameFlag || $("#addBtn_"+treeNode.id).length>0) return;
			var addStr = "<button type='button' class='add' id='addBtn_" + treeNode.id
				+ "' title='add node' onfocus='this.blur();'></button>";
			sObj.append(addStr);
			var btn = $("#addBtn_"+treeNode.id);
			if (btn) btn.bind("click", function(){
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				zTree.addNodes(treeNode, {id:(maxID + 1), pId:treeNode.id, name:"new node" + (newCount++)});
				return false;
			});
		};
		
		function fontCss(treeNode) {
			var aObj = $("#" + treeNode.tId + "_a");
			aObj.removeClass("copy").removeClass("cut");
			if (treeNode === curSrcNode) {
				if (curType == "copy") {
					aObj.addClass(curType);
				} else {
					aObj.addClass(curType);
				}			
			}
		}

		function beforeClick(treeId, treeNode) {
			showLog("[ "+getTime()+" beforeClick]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			return !treeNode.isCur;
		}

		var curSrcNode, curType;
		function setCurSrcNode(treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			if (curSrcNode) {
				delete curSrcNode.isCur;
				var tmpNode = curSrcNode;
				curSrcNode = null;
				fontCss(tmpNode);
			}
			curSrcNode = treeNode;
			if (!treeNode) return;

			curSrcNode.isCur = true;			
			zTree.cancelSelectedNode();
			fontCss(curSrcNode);
		}
		function copy(e) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes();
			if (nodes.length == 0) {
				alert("请先选择一个节点");
				return;
			}
			curType = "copy";
			showLog("[ "+getTime()+" copy]&nbsp;&nbsp;&nbsp;&nbsp; " + nodes[0].name);
			setCurSrcNode(nodes[0]);
		}
		function cut(e) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes();
			if (nodes.length == 0) {
				alert("请先选择一个节点");
				return;
			}
			curType = "cut";
			showLog("[ "+getTime()+" cut]&nbsp;&nbsp;&nbsp;&nbsp; " + nodes[0].name);
			setCurSrcNode(nodes[0]);
		}
		function paste(e) {
			if (!curSrcNode) {
				alert("请先选择一个节点进行 复制 / 剪切");
				return;
			}
			var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
			nodes = zTree.getSelectedNodes(),
			targetNode = nodes.length>0? nodes[0]:null;
			if (curSrcNode === targetNode) {
				alert("不能移动，源节点 与 目标节点相同");
				return;
			} else if (curType === "cut" && ((!!targetNode && curSrcNode.parentTId === targetNode.tId) || (!targetNode && !curSrcNode.parentTId))) {
				alert("不能移动，源节点 已经存在于 目标节点中");
				return;
			} else if (curType === "copy") {
				targetNode = zTree.copyNode(targetNode, curSrcNode, "inner");
			} else if (curType === "cut") {
				targetNode = zTree.moveNode(targetNode, curSrcNode, "inner");
				if (!targetNode) {
					alert("剪切失败，源节点是目标节点的父节点");
				}
				targetNode = curSrcNode;
			}
			setCurSrcNode();
			delete targetNode.isCur;
			zTree.selectNode(targetNode);
		}
		
		function removeHoverDom(treeId, treeNode) {
			$("#addBtn_"+treeNode.id).unbind().remove();
		};
		
		function addDiyDom(treeId, treeNode) {
			var aObj = $("#" + treeNode.tId + IDMark_A);
			var editStr = "<a id='diyBtn1_" +treeNode.id+ "' onclick='openUrl("+treeNode.id+")' class=''><img src='resources/images/6.png' border='0'></a>" ;
			aObj.after(editStr);
		}
		
		function openUrl(id){
			var options={height:300, width:580, minH:40, minW:50, total:20, max:false, mask:false, resizable:true, drawable:true, maxable:true,minable:true,fresh:true};
			$.pdialog.open("${ctx}/menu/edit/"+id+"?navtabid=${navtabid}", "menuInfo", "菜单信息",options);
		}
		
		function getmaxId(){
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var nodes = treeObj.transformToArray(treeObj.getNodes());
			var maxid=0;//获得当前树最大的id
			for(var i=0;i<nodes.length;i++){ 
			    if(nodes[i]["id"]>maxid){
			    	maxid=nodes[i]["id"];
			    }
			}
			return maxid;
		}
		
//-->
</SCRIPT>
	<style type="text/css">
.ztree li button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
	</style>
<div class="pageContent">
	<div class="pageFormContent nowrap" >
		<div style="float:left; margin:2px" class="fileQueue" layoutH="62" >
			<ul id="treeDemo" class="ztree"></ul>
		</div>
		<div style="float:left; margin:2px" class="fileQueue" layoutH="62"  >
			<ul id="log" class="log"></ul>
		</div>
	</div>
	<div class="formBar">
			<ul>
				<li><div class="button"><div class="buttonContent"><button type="button" id="copy">复制</button></div></div></li>
				<li><div class="button"><div class="buttonContent"><button type="button" id="cut">剪切</button></div></div></li>
				<li><div class="button"><div class="buttonContent"><button type="button" id="paste">粘贴</button></div></div></li>
				<li><div class="buttonActive"><div class="buttonContent"><button type="button" id="btnSvaeTree">提交</button></div></div></li>
				<li><div class="button"><div class="buttonContent"><button type="button" class="close">关闭</button></div></div></li>
			</ul>
	</div>
</div>